const router = require('koa-router')()
const koaBody = require('koa-body')();
const request = require('superagent'); //不要忘记npm install
const co = require('co');
var config=require('../config/app.config');
module.exports = router.get('/invited/:id', koaBody, co.wrap(function*(ctx) {
    console.log(ctx.request);
    // => POST body
    let  id = ctx.params.id;
    let appid = config.appid;
    let redirect_uri = config.redirect_uri+'inviter?'+id;
    let wxUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='+appid+'&redirect_uri='+redirect_uri+'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect'
    // 调用微信接口拿到code接口获取用户授权信息
    var res = yield request
    .get(wxUrl)
    .send(ctx.request.body)
    .set('X-API-Key', 'foobar')
    console.log(res);

  })).get('/getWxCode',co.wrap(function*(ctx) {
    /**微信授权登陆完成重定向 
     * 1.获取授权code
     * 2、带上当前商户或平台的编号请求后台
     * 3、获取到微信授权用户信息重定向到首页进行缓存
     */
    console.log(ctx.query)
    // => POST body
    //ctx.body = JSON.stringify(ctx.request.body);
    //console.log(ctx.body)
    // 调用远程接口获取用户授权信息
    console.log(ctx.request.body)
    var res = yield request
    .post(config.host+'/api/crm/weixin/getWxUser')
    .send({ orgNo: config.orgNo, merchantNo: config.merchantNo, code: ctx.query.code })
    .set('X-API-Key', 'foobar')
    .set('Accept', 'application/json')
    .set('Content-Type', 'application/json');
    console.log(res.body);
    ctx.render('index', { customerId: 'Nunjucks'});
  })).post('/createInviteQrCode', koaBody, co.wrap(function*(ctx) {
    console.log(ctx.request.body);
    // => POST body
    //ctx.body = JSON.stringify(ctx.request.body);
    //console.log(ctx.body)
    // 调用远程接口获取用户授权信息
    console.log(ctx.request.body)
    var res = yield request
    .post(config.host+'/api/crm/customer/createInviteQrCode')
    .send(ctx.request.body)
    .set('X-API-Key', 'foobar')
    .set('Accept', 'application/json')
    .set('Content-Type', 'application/json');
    ctx.response.body = res.body;
    //ctx.render('index', { title: 'Nunjucks', content: 'Feifeiyu yeah!' });
  }));
